<template>
  <el-dialog v-model="dialogVisible" title="添加标签" width="30%" :before-close="handleClose">
    <div class="share-dialog">
      <el-form ref="ruleFormRef" label-width="80px" :model="ruleForm" :rules="rules">
        <!--   -->
        <el-form-item label="标签" prop="labels">
          <el-tree-select default-expand-all node-key="id" filterable multiple v-model="ruleForm.labels" show-checkbox
            :data="treeData" :props="{
              label: 'name',
            }" style="width: 100%" placeholder="选择标签" clearable>
          </el-tree-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { listApi } from "@/plugins/api/customer/setup/fourth";
import { addLabelApi } from "@/plugins/api/customer/manage/my";
const props = defineProps({
  hasLabel: {
    type: Array,
    default: [],
  },
});
let ruleForm = ref({});
let rules = {
  labels: [
    {
      required: true,
      message: "选择标签",
      trigger: "change",
    },
  ],
};
let dialogVisible = ref(false);
function handleClose(done) {
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => { });
}

let ruleFormRef = ref(null);
function initFun(row) {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
  ruleForm.value = {};
  ruleForm.value.customer_id = row.id;
  ruleForm.value.labels = props.hasLabel.map((item) => {
    return item.label_id;
  });
  dialogVisible.value = true;
}
const emit = defineEmits(["refreshList"]);
function submit() {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      let data = props.hasLabel.map((item) => {
        return item.label_id;
      });
      let arr = [];
      ruleForm.value.labels.forEach((item, i) => {
        if (data.indexOf(item) == -1) {
          arr.push(item);
        }
      });
      let str = JSON.stringify(ruleForm.value);
      let obj = JSON.parse(str);
      obj.labels = arr;
      addLabelApi(obj).then((data) => {
        ElMessage.success("添加成功！");
        dialogVisible.value = false;
        emit("refreshList");
      });
    }
  });
}

let treeData = ref([]);
function getLabel() {
  listApi().then((res) => {
    treeData.value = res;
  });
}
onMounted(() => {
  getLabel();
});
defineExpose({
  initFun,
});
</script>
<style scoped lang="scss">
.share-dialog {
  .form-item-style {
    width: 100%;
    margin-right: 0;

    :deep(.el-input) {
      width: 100%;
    }
  }
}
</style>
